#include "stdafx.h"
#include "RWFile.h"
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
#include <dbghelp.h>
#include <shlwapi.h>
#pragma comment(lib, "dbghelp")
#pragma comment(lib, "shlwapi")

void DecKFXArchive(string path)
{
	string fileSave = path + ".txt";
	string kBuff;
	string kBuffDec;
	if (RWFile::LoadFile(path, kBuff))
	{
		int len = kBuff.length();
		if (len < 52)
		{
			return;
		}
		BYTE* data = (BYTE*)kBuff.c_str();
		if (strcmp((const char *)data, "KFXArchive"))
		{
			kBuffDec.resize(50 + len, 0);
			BYTE* dst = (BYTE*)kBuffDec.c_str();
			strcpy((char*)dst, "KFXArchive");
			dst += 50;
			for (size_t i = 0; i < kBuff.size(); i++)
			{
				dst[i] = data[i] ^ 0x9D;
			}
		}
		else
		{
			data += 50;
			BYTE a = data[0] ^ 0x9D;
			BYTE b = data[1] ^ 0x9D;
			if (a != -1 || b != -2)
			{
				kBuffDec.resize(len - 50);
				BYTE* dst = (BYTE*)kBuffDec.c_str();
				for (size_t i = 0; i < kBuffDec.size(); i++)
				{
					dst[i] = data[i] ^ 0x9D;
				}
			}
			else
			{
				data += 2;
				WCHAR WideCharStr = 0;
				CHAR MultiByteStr = 0;
				int chIdx = 0;
				char firstCh = data[chIdx];
				char nextCh = firstCh;
				char nextBCh = 0;
				if (firstCh != -1)
				{
					do
					{
						nextBCh = data[++chIdx];
						WideCharStr = (BYTE)(nextCh ^ 0x9D) + (((BYTE)nextBCh ^ 0xFF9D) << 8);
						MultiByteStr = 0;
						WideCharToMultiByte(0, 0, &WideCharStr, 1, &MultiByteStr, 3, 0, 0);
						kBuffDec.append(1, MultiByteStr);
						nextCh = data[++chIdx];
					} while (nextCh != -1);
				}
			}
		}
		RWFile::SaveFile(path, kBuffDec);
	}
}

int main(int argc, char **argv)
{
	if (argc == 2)
	{
		string path = argv[1];
		if (!PathFileExists(path.c_str()))
		{
			printf("file not found!!!");
			return -1;
		}
		DecKFXArchive(path);
	}
    return 0;
}